import userApi, { CaptchaData, LoginParamData, UserData} from '@/api/user'
import { defineStore } from 'pinia'

interface UserInfoData {
  captcha:CaptchaData
  token:string
  userInfo:UserData
}

export let useUserInfoStore = defineStore('user',{
  state() : UserInfoData {
    return {
      captcha:{
        image:"",
        key:""
      },
      token:localStorage.getItem('token_key') || "",
      userInfo:{
        name:"",
        avatarUrl:""
      }
    }
  },
  actions: {
    //获取验证码信息
    async getCaptchaCode(){
      let { data } = await userApi.getCaptchaCode();
      this.captcha = data;
    },
    //验证登录
    async checkLogin(loginParam : LoginParamData){
      let { data } = await userApi.checkLogin(loginParam);
      this.token = data;
      //将令牌存储到localStorage中
      localStorage.setItem('token_key',data);
    },
    //获取当前登录的用户信息
    async getUserInfo(){
      let { data } = await userApi.getUserInfo();
      this.userInfo = data;
    },
    //退出登录
    logout(){
      this.token = "";
      localStorage.removeItem('token_key');
      this.userInfo = {
        name:"",
        avatarUrl:""
      }
    }
  }
})